package net.zjitc.tree;

/**
 * 第九章 查找9.2.2 二分查找法
 */
public class CH09_02 {
    public static void main(String[] args) {
        int[] data = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        int val = 5;//查找的值
        int resylt = search(data, val);
        System.out.println(resylt);
    }

    private static int search(int[] data, int val) {
        int left = 0, right = data.length - 1, mid = 0;

        while (left <= right) {
            mid = (left + right) / 2;
            if (val == data[mid]) {
                return data[mid];
            } else if (val > data[mid]) {
                left = mid + 1;
                mid = (left + right) / 2;
            } else if (val < data[mid]) {
                right = mid - 1;
                mid = (left + right) / 2;
            }
        }
        return -1;
    }
}
